package com.ken.blog.controller.web;

import com.ken.blog.domain.Article;
import com.ken.blog.domain.Category;
import com.ken.blog.domain.ArticleRepository;
import com.ken.blog.domain.CategoryRepository;
import com.ken.blog.tools.Pagination;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Map;

@Controller
public class HomeController {
    @Autowired
    private ArticleRepository articleRepository;

    @RequestMapping("/")
    public ModelAndView index(Model model, String page) {
        ModelAndView mv = new ModelAndView("/web/home");

        //处理分页请求
        int pageSize = Pagination.getPageSize(page);
        Pageable pageable = new PageRequest(pageSize, 3);
        Page<Article> pageList = articleRepository.findAll(pageable);

        List<Article> articleList = pageList.getContent();
        //分页功能
        Map pagination = Pagination.simgle(pageList.getTotalPages(), pageSize + 1);

        mv.addObject("pagination", pagination);
        mv.addObject("articleList", articleList);

        return mv;
    }
}
